package com.mes.web.controller.system;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.mes.common.core.domain.AjaxResult;
import com.mes.common.core.domain.model.LoginUser;
import com.mes.common.utils.SecurityUtils;
import com.mes.framework.web.service.MobileLoginService;
import com.mes.framework.web.service.TokenService;
import com.mes.system.domain.LoginParams;
import com.mes.system.domain.bo.EncryptedDataBo;
import com.mes.system.domain.bo.LoginReqBo;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录控制器
 *
 * @author SK
 * @since 2018/6/13
 */
@RestController
@RequestMapping("/mobile/login")
public class LoginController{

    @Autowired(required = false)
    private TokenService tokenService;

    @Autowired(required = false)
    private MobileLoginService loginService;

    @Qualifier("MaService")
    @Autowired
    private WxMaService maService;

    @Value("${wx.appId}")
    private String appId;

    @Autowired
    private StringRedisTemplate template;



    /**
     * 会员登录
     * @return -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误
     */
    @PostMapping("/loginByPassword")
    @ResponseBody
    public AjaxResult loginByPassword(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phoneNo = request.getParameter("phoneNo");
        String validCode = request.getParameter("validCode");
        String loginType = request.getParameter("loginType");
        // 登录结果
        LoginParams loginParams = new LoginParams();
        loginParams.setUsername(username);
        loginParams.setPassword(password);
        loginParams.setPhoneNo(phoneNo);
        loginParams.setValidCode(validCode);
        loginParams.setLoginType(loginType);
        return loginService.login(loginParams);
    }
    /**
     * 发送验证码
     */
    @PostMapping("/sendCode")
    @ResponseBody
    public AjaxResult sendRegisterCode(HttpServletRequest request) {
        String phoneNo = request.getParameter("phoneNo");
        String validCodeType = request.getParameter("validCodeType");
        // 登录结果
        LoginParams loginParams = new LoginParams();
        loginParams.setPhoneNo(phoneNo);
        loginParams.setValidCodeType(validCodeType);
        return loginService.sendCode(loginParams);
    }

    @GetMapping("/logout")
    @ResponseBody
    public AjaxResult logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(null != loginUser){
            tokenService.delLoginUser(loginUser.getToken(),loginUser.getUserId());
        }
        return AjaxResult.success("退出成功！");
    }

    /**
     * 登陆接口
     */
    @ApiOperation(value = "登录")
    @PostMapping("/wxLogin")
    @ResponseBody
    public AjaxResult login( HttpServletRequest request){
        String code = request.getParameter("code");
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("code不能为空");
        }
        if (maService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
        }
        try {
            WxMaJscode2SessionResult session = maService.getUserService().getSessionInfo(code);
//            Map<String, Object> map =new HashMap<>();
            return AjaxResult.success(session);
        } catch (WxErrorException e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @ApiOperation(value = "获取手机号码")
    @PostMapping("/phone")
    @ResponseBody
    public AjaxResult phone(HttpServletRequest request) {
        String encryptedData = request.getParameter("encryptedData");
        String iv = request.getParameter("iv");
//        String sessionKey = request.getParameter("sessionKey");
        String code = request.getParameter("code");
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("code不能为空");
        }
        if (maService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
        }
        try {
            WxMaJscode2SessionResult session = maService.getUserService().getSessionInfo(code);
            WxMaPhoneNumberInfo phoneNoInfo = maService.getUserService().getPhoneNoInfo(session.getSessionKey(),encryptedData, iv);
//            LoginParams loginParams = new LoginParams();
//            loginParams.setPhoneNo(phoneNoInfo.getPhoneNumber());
//            loginParams.setUsername(phoneNoInfo.getPhoneNumber());
//            loginParams.setPassword(phoneNoInfo.getPhoneNumber());
//            loginParams.setLoginType("1");
//            return loginService.login(loginParams);

            return loginService.phoneLogin(phoneNoInfo.getPhoneNumber());

        } catch (WxErrorException e) {
            return AjaxResult.error(e.getMessage());
        }
//        ValueOperations<String, String> opsForValue = template.opsForValue();
//        String sessionKey =opsForValue.get("SessionKey"+ SecurityUtils.getUserId());
//        phoneNoInfo.getPhoneNumber();
    }
}
